import { atom } from 'recoil';
import { SignResponseVo } from 'src/models/sign-response-vo';
import { http, i18n } from 'src/utils';
import { SiderTheme } from 'antd/es/layout/Sider';

const locales = i18n.locales();

export const appStore = atom<{
  language: string;
  title: string;
  theme: SiderTheme;
  locales: typeof locales;
}>({
  key: 'app/$$/store',
  default: {
    title: '慧聚可视化资产管理系统',
    language: i18n.locale(),
    theme: 'light',
    locales,
  },
});

const cacheUserInfoKey = localStorage.getItem('accessToken');

let init: SignResponseVo | null = null;

if (cacheUserInfoKey) {
  const cacheUserInfo = localStorage.getItem(cacheUserInfoKey);
  if (cacheUserInfo) {
    try {
      init = JSON.parse(cacheUserInfo);
      if (init) {
        http.defaults.headers.common['Authorization'] =
          'Bearer ' + init.accessToken;
      }
    } catch (e) {
      console.error(e);
    }
  }
}

export const appUserStore = atom<SignResponseVo | null>({
  key: 'app/$$/user-store',
  effects: [
    ({ onSet }) => {
      onSet((newValue) => {
        if (newValue?.accessToken) {
          localStorage.setItem('accessToken', newValue.accessToken);
          localStorage.setItem(newValue.accessToken, JSON.stringify(newValue));
          http.defaults.headers.common['Authorization'] =
            'Bearer ' + newValue.accessToken;
        } else {
          localStorage.removeItem('accessToken');
          return newValue;
        }
      });
    },
  ],
  default: init,
});
